/* Tables2And4.do */

******************
* Variables to hold model results to eventually
* build big table.
******************
qui gen rc_state=""
label var rc_state "State"
qui gen rc_estimate=""
label var rc_estimate "Statistic"
qui gen rc_1=.
label var rc_1 "All Precincts, OLS"
qui gen rc_2=.
label var rc_2 "All Precincts, Quantile Regression"
qui gen rc_3=.
label var rc_3 "Bottom Tercile, 2012 Republican Vote"
qui gen rc_4=.
label var rc_4 "Middle Tercile, 2012 Republican Vote"
qui gen rc_5=.
label var rc_5 "Top Tercile, 2012 Republican Vote"

******************
* Variables to store OLS results to eventually build
* simple table with each column = one state.
******************
qui gen simptab_varname = ""
qui gen simptab_FL = .
qui gen simptab_GA = .
qui gen simptab_MI = .
qui gen simptab_NV = .
qui gen simptab_OH = .
qui gen simptab_PA = .


******************
* Loop over states and build tables/run regressions.
******************

levelsof state, local(states)

local stloopctr=1

foreach stctr of local states {

	di "STATE=`stctr'"
	replace rc_state="`stctr'" in `stloopctr'
  * Set up outreg latex table.
  local notes = ""
  local outregfile = "$TABLELOC/ElecChange-FullRegressionResults-`stctr'"

	local pctr=(`stloopctr'+1)
	local mctr=(`stloopctr'+2)
	local comp=(`stloopctr'+3)
	local conv=(`stloopctr'+4)
	local ratio=(`stloopctr'+5)
	
	replace rc_estimate="N" in `pctr'
	replace rc_estimate="Avg. Electoral Change (Sample Mean)" in `mctr'
	replace rc_estimate="Est. Avg. Composition Effect" in `comp'
	replace rc_estimate="Est. Avg. Conversion Effect" in `conv'
	replace rc_estimate="Ratio of Composition to Conversion" in `ratio'
		
	forvalues modelctr=1(1)5 {

		if `modelctr'==1 {
			* Model: All precincts, OLS.
			* Breaking present both down among parties, as well as appearing/disappearing
			regress gop_vote_change Total_Voters_2012_Prct PresBothNetDem16TO PresBothNetGOP16TO PresBothNetOTH16TO P12*_V1*_* P16*_V1*_* if state=="`stctr'" , robust
		}
		else if `modelctr'==2 {
		  * Model: All precincts, Quantile regression.
			qreg  gop_vote_change Total_Voters_2012_Prct PresBothNetDem16TO PresBothNetGOP16TO PresBothNetOTH16TO P12*_V1*_* P16*_V1*_* if state=="`stctr'",  vce(robust) nolog
		}
		else if `modelctr'==3 {
			* Model: GOP tercile 1, OLS.
			regress  gop_vote_change Total_Voters_2012_Prct PresBothNetDem16TO PresBothNetGOP16TO PresBothNetOTH16TO P12*_V1*_* P16*_V1*_* if state=="`stctr'" & t3_2012voteshare==1, robust
		}
		else if `modelctr'==4{
			* Model: GOP tercile 1, OLS.
			regress  gop_vote_change Total_Voters_2012_Prct PresBothNetDem16TO PresBothNetGOP16TO PresBothNetOTH16TO P12*_V1*_* P16*_V1*_* if state=="`stctr'" & t3_2012voteshare==2, robust
		}
		else if `modelctr'==5 {
			* Model: GOP tercile 1, OLS.
			regress  gop_vote_change Total_Voters_2012_Prct PresBothNetDem16TO PresBothNetGOP16TO PresBothNetOTH16TO P12*_V1*_* P16*_V1*_* if state=="`stctr'" & t3_2012voteshare==3, robust
		}
		else {
			error!
		}

    ************************
		* Calculate countfactual compositional and conversion effects
    ************************
		gen est_effectcomp_pboth=_b[PresBothNetDem16TO]*PresBothNetDem16TO+_b[PresBothNetGOP16TO]*PresBothNetGOP16TO+_b[PresBothNetOTH16TO]*PresBothNetOTH16TO if e(sample)
		gen est_effectcomp_all=est_effectcomp_pboth + _b[P12_V12_DEM]*P12_V12_DEM + _b[P12_V12_GOP]*P12_V12_GOP + _b[P12_V12_OTH]*P12_V12_OTH + _b[P16_V16_DEM]*P16_V16_DEM + _b[P16_V16_GOP]*P16_V16_GOP + _b[P16_V16_OTH]*P16_V16_OTH if e(sample)
		gen est_effectconversion=_b[_cons]+ _b[Total_Voters_2012_Prct]*Total_Voters_2012_Prct if e(sample)
		
		foreach var of varlist est_effectcomp_pboth est_effectcomp_all est_effectconversion {
			qui summ `var'
			local l_`var' = `r(mean)'
			local se_`var' = `r(sd)'/sqrt(`r(N)')
			drop `var'
		}
		* End calculate countfactual compositional and conversion effects

    * Save regression results to regression table.
		if `modelctr'==1 {
			outreg2 using "`outregfile'.tex", $OUTREG2OPTIONS ctitle("All precincts,OLS") addnote(`notes') replace
		}
		else if `modelctr'==2 {
			 outreg2 using "`outregfile'.tex", $OUTREG2OPTIONS ctitle("All precincts,Quantile,regression") addnote(`notes') append
		}
		else if `modelctr'==3 {
			 outreg2 using "`outregfile'.tex", $OUTREG2OPTIONS ctitle("2012 GOP ,vote tercile 1,OLS") append
		}
		else if `modelctr'==4 {
			 outreg2 using "`outregfile'.tex", $OUTREG2OPTIONS ctitle("2012 GOP ,vote tercile 2,OLS") append
		}
		else if `modelctr'==5 {
			 outreg2 using "`outregfile'.tex", $OUTREG2OPTIONS ctitle("2012 GOP ,vote tercile 2,OLS") append
		}
		else {
			error!
		}

		* Store relevant summary stats/estimates in local variables to write to latex table big latex table.
		replace rc_`modelctr'=e(N) in `pctr'
		qui summ gop_vote_change if e(sample)
		replace rc_`modelctr'=r(mean) in `mctr'
		replace rc_`modelctr'=`l_est_effectcomp_all' in `comp'
		replace rc_`modelctr'=r(mean) - `l_est_effectcomp_all' in `conv'
			
		replace rc_`modelctr'=`l_est_effectcomp_all'/(r(mean) - `l_est_effectcomp_all') in `ratio'
    
    
    * Store OLS summary stats for this state for simple table.
		if `modelctr'==1 {
      qui summ gop_vote_change if e(sample)
      qui replace simptab_varname = "Avg. Electoral Change (Sample Mean)" in 1
      qui replace simptab_`stctr' = r(mean) in 1
      qui replace simptab_varname = "Est. Avg. Composition Effect" in 2
      qui replace simptab_`stctr' = `l_est_effectcomp_all' in 2
      // qui replace simptab_varname = "Standard Error, Composition Effect" in 3
      // qui replace simptab_`stctr' = `se_est_effectcomp_all' in 3
      qui replace simptab_varname = "Est. Avg. Conversion Effect" in 3
      qui replace simptab_`stctr' = r(mean) - `l_est_effectcomp_all' in 3
      qui replace simptab_varname = "Ratio of Composition to Conversion" in 4
      qui replace simptab_`stctr' = `l_est_effectcomp_all'/(r(mean) - `l_est_effectcomp_all') in 4
      qui replace simptab_varname = "N precincts" in 5
      qui replace simptab_`stctr' = e(N) in 5
    }

	}
	
	local stloopctr=`stloopctr'+6
}

*******************
* Full table with results from each regression model
* and data subset.
*******************
preserve
keep rc_*
keep in 1/36

* Create a latex string for each row.
qui egen latex = concat(rc_state rc_estimate), punct(" & ")
* For N rows with no decimals.
qui egen latexN = concat(latex rc_1-rc_5), format(%9.0f) punct(" & ")
* For Mean and Intercept rows, one decimal.
qui egen latexMnInt = concat(latex rc_1-rc_5), format(%9.1f) punct(" & ")
* For Ratio two decimal.
qui egen latexRatio = concat(latex rc_1-rc_5), format(%9.2f) punct(" & ")
* For SE rows, one decimal plus leading and trailing parens.
qui egen latexSE = concat(latex rc_1-rc_5), format(%9.1f) punct(") & (")
* Remove ) from Error column, add ) at end of line.
qui replace latexSE = subinstr(latexSE,"Error)","Error",.)+")"

* Replace latex column with appropriate version.
qui replace latex = latexN if rc_estimate == "N"
qui replace latex = latexMnInt if regexm(rc_estimate,"Composition|Conversion|Intercept|Mean")
qui replace latex = latexRatio if regexm(rc_estimate,"Ratio")
qui replace latex = latexSE if regexm(rc_estimate,"Error")
* Remove excessive "standard error" text.
*qui replace latex = subinstr(latex,"Standard Error","",.)
* Append with \\ and write out.
qui replace latex = latex + " \\"
qui outsheet latex using "$TABLELOC/CountsSummaryPaperTable.tex", replace noquote nonames

* Write out variable names as table header to latex
tempname fh
file open `fh' using "$TABLELOC/HeaderCountsSummaryPaperTable.tex", write replace
local mystring = ""
foreach v of varlist rc_* {
  local templabel : var label `v'
  local mystring = "`mystring'`templabel' & "
}
* Remove ending &.
local mystring = "`mystring'ZZZ" 
local mystring = subinstr("`mystring'","& ZZZ","",.)
file write `fh' "`mystring' \\" _newline
file close `fh'
restore

*******************
* Simple table holding OLS results only. Each column = one state.
*******************
summ simptab_*
* Create latex rows.
local fmt "%9.1f"
gen str250 latex = simptab_varname + " & " +  string(simptab_FL,"`fmt'") + " & " +  string(simptab_GA,"`fmt'") + " & " +  string(simptab_MI,"`fmt'") + " & " +  string(simptab_NV,"`fmt'") + " & " +  string(simptab_OH,"`fmt'") + " & " +  string(simptab_PA,"`fmt'") + " \\ "
* For effects, zero decimal.
local fmt "%9.0f"
qui replace latex = simptab_varname + " & " +  string(simptab_FL,"`fmt'") + " & " +  string(simptab_GA,"`fmt'") + " & " +  string(simptab_MI,"`fmt'") + " & " +  string(simptab_NV,"`fmt'") + " & " +  string(simptab_OH,"`fmt'") + " & " +  string(simptab_PA,"`fmt'") + " \\ " if regexm(simptab_varname,"Avg.")


li latex in 1/5
* Write to tex file.
qui outsheet latex in 1/4 using "$TABLELOC/CountsSimpleTable.tex", replace noquote nonames
